<?php

/**
 * @author    1054229380@qq.com
 * @since    2017-7-3
 * @desc 用户类
 * */
require APP_ROOT . "/libs/member.class.php";

class sysUser
{

    var $tableName; //表名
    var $trueName; //真实姓名
    var $sex; //性别
    var $loginTimes; //登陆次数
    var $createTime; //创建时间

    function __construct()
    {
        $dbTable_prefix = "cj_";
        $dbTable_name = "sysuser";
        $this->tableName = $dbTable_prefix . $dbTable_name;
        $this->auth = new auth();
    }

    /**
     * 保存数据信息
     * */
    function save($postArr)
    {
        $tableName = $this->tableName;
        $_infoId = $postArr[0]['postData']['id'];
        if ($_infoId == 0) {
            $postArr[0]['postData']['createTime'] = time();
        }

        //e($postArr);
        //exit();
        $backArr = sql::postToSql($tableName, $postArr);
        $hasError = $backArr['hasError'];
        $sqlArr = $backArr['sqlArr'];
        if ($hasError == "y") {
            return false;
        } else {
            $sql = $sqlArr[0];
            if (db::runsql($sql)) {
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * 管理员登陆验证
     * @param @userName 用户名
     * @param @passWord 密码2
     * @return true,false
     * */
    function loginCheck($userName, $passWord)
    {
        $tableName = $this->tableName;
        $passWord = md5($passWord);
        $searchCondition[] = "userName='$userName'";

        $whereStr = db::convertSearchToSql($searchCondition);

        $userInfo = db::getInfo(array(
            "tableName" => $tableName,
            "selectField" => "id,userName,userType,password",
            "whereCondition" => $whereStr
        ));
        $_SESSION["BackUserInfo"] = $userInfo;
        if ($userInfo && $passWord == $userInfo['password']) {
            unset($userInfo['password']);

            $authList = $this->auth->getAuthList('ADMIN');
            $topMenu = array();
            $subMenu = array();
            $authUrl = array();
            foreach ($authList as $key => $val) {
                if ($val['parId'] == 0) {
                    $topMenu[] = $val;
                } else {
                    $subMenu[] = $val['classId'];
                    $authUrl[] = $val['url'];
                }
            }
            $_SESSION['h_authList'] = array(
                'isSuper' => 1,
                'topMenu' => $topMenu,
                'subMenu' => $subMenu,
            );
            $this->initUserLoginInfo($userInfo);
            return $userInfo;
        } else {
            $userInfo = db::getInfo(array(
                "tableName" => 'cj_member',
                "selectField" => "id,userName,userType,password,authId",
                "whereCondition" => $whereStr
            ));
            if ($userInfo && $passWord == $userInfo['password']) {
                unset($userInfo['password']);
                $g = db::update('cj_member', array('sessionId' => session_id()), "Where id={$userInfo['id']}");
                cache::setUpdateTime('cj_member');
                //获取用户分组权限
                $authIds = para::getPara('authInfo', $userInfo['authId']);
                if ($authIds[0]['paraValue'] != '') {
                    $authList = $this->auth->getAuthList('ADMIN', $authIds[0]['paraValue']);
                } else {
                    sysMsg::error('对不起,您没有登录后台的权限');
                }
                $topMenu = array();
                $subMenu = array();
                $authUrl = array();
                $authPara = array();
                foreach ($authList as $key => $val) {
                    if ($val['parId'] == 0) {
                        $topMenu[] = $val;
                    } else {
                        if ($val['classId'] != 0) {
                            $authPara[$val['classId']] = array($val['url']);
                            foreach ($authList as $k => $v) {
                                if ($v['broId'] == $val['id']) {
                                    $authPara[$val['classId']][] = $v['url'];
                                }
                            }
                        }

                        $subMenu[] = $val['classId'];
                        $authUrl[] = $val['url'];
                    }
                }
                $_SESSION['h_authList'] = array(
                    'isSuper' => 0,
                    'topMenu' => $topMenu,
                    'subMenu' => $subMenu,
                    'authUrl' => $authUrl,
                    'authPara' => $authPara
                );

                $this->initUserLoginInfo($userInfo);
                return $userInfo;
            } else {
                return false;
            }
        }
    }

    /**
     * 判断用户是否存在
     * */
    function userIsExist($userName)
    {
        $tableName = $this->tableName;
        $searchCondition[] = "userName='$userName'";
        $whereStr = db::convertSearchToSql($searchCondition);
        $userInfo = db::getInfo(array(
            "tableName" => $tableName,
            "selectField" => "id,userName,userType",
            "whereCondition" => $whereStr
        ));
        $userId = isset($userInfo['id']) ? $userInfo['id'] : "";
        if ($userId != "") {
            return $userInfo;
        } else {
            return false;
        }
    }

    /**
     * 初始化用户登陆信息
     * */
    function initUserLoginInfo($userInfo)
    {

        $_SESSION['h_userInfo'] = array(
            "id" => $userInfo['id'], //用户ID
            "userName" => $userInfo['userName'], //用户名
        );
    }

    /**
     * 检测用户名及密码是否正确
     * */
    function userPassWordCheck($userId, $passWord)
    {
        $tableName = $this->tableName;
        $passWord = md5($passWord);
        $searchCondition[] = "id='$userId'";
        $searchCondition[] = "passWord='$passWord'";
        $whereStr = db::convertSearchToSql($searchCondition);
        $userInfo = db::getInfo(array(
            "tableName" => $tableName,
            "selectField" => "id",
            "whereCondition" => $whereStr
        ));
        $userId = isset($userInfo['id']) ? $userInfo['id'] : "";
        if ($userId != "") {
            return $userInfo;
        } else {
            return false;
        }
    }

    /**
     * 删除
     * @param @infoIds  删除信息IDS
     * @return bool
     * */
    function del($infoIds)
    {
        $tableName = $this->tableName;
        $sql = "delete from {$tableName} where id in($infoIds) and isCheck=0";
        return db::runsql($sql);
    }

    /**
     * 设置状态，审核，置顶
     * @return bool
     * */
    function setStatus($setType, $statusData, $infoId)
    {
        $tableName = $this->tableName;
        if ($setType == "setCheck") {
            $fieldName = "isCheck";
        }
        $sql = "update {$tableName} set {$fieldName}=$statusData where id in($infoId)";
        cache::setUpdateTime($tableName);
        return db::runsql($sql);
    }

    /**
     * 设置用户新密码
     * */
    function setNewPassWord($userId, $oldPassWord, $newPassWord)
    {
        $tableName = $this->tableName;
        if ($this->userPassWordCheck($userId, $oldPassWord)) {
            $newPassWord = md5($newPassWord);
            $sql = "update $tableName set passWord='$newPassWord' where id=$userId";
            if (db::runsql($sql)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    /**
     * 获取授权用户信息
     * */
    function getLoginUserInfo()
    {
        return $_SESSION['h_userInfo'];
    }

    /**
     * 授权验证
     * */
    function authorityCheck()
    {
        //超级管理员无需验证session_id
        if (!isset($_SESSION['h_userInfo'])) {
            if (IS_AJAX()) {
                sysMsg::g("你还没有登陆或超过有效时间");
            } else {
                linkTo(_RURL . "/sysad/sysUser/login");
            }
        }
        if ($_SESSION['h_authList']['isSuper'] != 1) {
            $userId = $_SESSION['h_userInfo']['id'];
            $userInfo = db::getInfo(array(
                'returnCache' => true,
                "tableName" => 'cj_member',
                "selectField" => 'sessionId',
                "whereCondition" => "where id=$userId"
            ));
            if (!isset($_SESSION['h_userInfo']) || $userInfo['sessionId'] != session_id()) {
                session_destroy();
                if (IS_AJAX()) {
                    sysMsg::g("你还没有登陆或超过有效时间");
                } else {
                    linkTo(_RURL . "/sysad/sysUser/login");
                }
            }
        }
    }

    /**
     * 获取指定用户自定义信息
     * @param @_userId 用户ID
     * */
    public function getInfo($_userId, $_selField = '*')
    {
        $tableName = $this->tableName;
        $_tempInfo = db::getInfo(array(
            "tableName" => $tableName,
            "selectField" => $_selField,
            "whereCondition" => "where id=$_userId"
        ));
        return $_tempInfo;
    }

    /**
     * 获取用户例表信息
     * */
    public function getList($config)
    {
        $tableName = $this->tableName;
        $selectField = $config['selectField']; //搜索字段
        $orderBy = $config['orderBy']; //排序方式
        $pageSize = $config['pageSize']; //每页数量
        $page = $config['page']; //页次
        $searchCondition = $config['searchCondition']; //搜索条件
        $linkStr = $config['linkStr']; //页码自定链接，可为空
        $whereStr = db::convertSearchToSql($searchCondition);
        if ($linkStr == "") {
            $linkStr = db::convertSearchToLinkStr($linkStr);
        }
        $offSet = ($page - 1) * $pageSize;


        $_tempIdArr = db::getIds(array(
            "tableName" => $tableName,
            "selectField" => "id",
            "whereCondition" => $whereStr,
            "orderBy" => $orderBy,
            "offSet" => $offSet,
            "limitRows" => $pageSize
        ));

        $listIds = $_tempIdArr['ids']; //查询结果ID集
        $sql = $_tempIdArr['sql']; //调试用SQL
        //echo $sql."<br>";
        $totalRows = db::getCount($tableName, $whereStr);
        $pageCount = ceil($totalRows / $pageSize);
        $listArr = db::getArr(array(
            "tableName" => $tableName,
            "selectField" => "*",
            "whereCondition" => "where id in($listIds)",
            "orderBy" => $orderBy
        ));
        $pageStr = page::pagelist($pageCount, $page, $totalRows, $pageSize, $linkStr, 1); //分页信息
        $backArr['totalRows'] = $totalRows;
        $backArr['pageCount'] = $pageCount;
        $backArr['list'] = $listArr;
        $backArr['pageStr'] = $pageStr;
        $backArr['listIds'] = $listIds;
        return $backArr;
    }

    /**
     * 获取指定用户信息
     * @param @_userId 用户ID
     * */
    function getUserInfo($_userId)
    {
        return self::getInfo($_userId, "id,userName,trueName");
    }

    /**
     * 获取指定用户全部信息
     * @param @_userId 用户ID
     * */
    function getFullUserInfo($_userId)
    {
        return self::getInfo($_userId, "id,userName,trueName,sex,loginTimes,createTime");
    }

    /**
     * 删除用户
     * @param @_userId 用户ID
     * */
    function delUser($_userId)
    {
        $tableName = $this->tableName;
    }

}

?>